﻿// Decompiled with JetBrains decompiler
// Type: DnProcessSimulateCommands.Flexibles.CApCableAttachmentsUserControl
// Assembly: DnProcessSimulateCommands, Version=2402.0.0.890, Culture=neutral, PublicKeyToken=null
// MVID: A885D881-AEDF-447E-852A-6F13102E089C
// Assembly location: C:\Program Files\Tecnomatix_2402\eMPower\DotNetCommands\DnProcessSimulateCommands.dll

using System;
using System.CodeDom.Compiler;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Markup;
using Tecnomatix.Engineering;
using Tecnomatix.Engineering.Ui;
using Tecnomatix.Engineering.Ui.WPF;


namespace DnProcessSimulateCommands.Flexibles;

public class CApCableAttachmentsUserControl : UserControl, IComponentConnector, IStyleConnector
{
  private bool m_isControlLoading;
  private bool m_isFrameNameChanging;
  internal StackPanel attachmentsStackPanel;
  internal DataGrid fgAttachmentFlexGrid;
  internal DataGridTemplateColumn attachmentLengthTitle;
  internal Grid addAttachmentGrid;
  internal Button btnAddAttachment;
  internal Button btnRemoveAttachment;
  internal Button btnEditAttachment;
  private bool _contentLoaded;

  public CApCableAttachmentsUserControl()
  {
    this.m_isControlLoading = true;
    this.AttachmentViewModel = new CApFLEXCableAttachmentViewModel();
  }

  public event CApCableEventHandler AttachmentDialogOpened;

  public event CApCableEventHandler AttachmentDialogClosed;

  public CApFLEXCableAttachmentViewModel AttachmentViewModel { get; set; }

  public ICApFLEXCableAttributeViewModel AttributeViewModel { get; set; }

  public CUiFLEXAttachmentEditorWindow NewAttachmentWindow { get; set; }

  public CApFlexParameterController ParameterController { get; set; }

  internal CApCableFrameAttachmentRetriever FrameAttachmentRetriever { get; set; }

  public CApFLEXFrameValidator FrameValidator { get; set; }

  private List<ITxLocatableObject> AttachmentFrames { get; set; }

  public bool IsAttachmentDialogLaunching { get; set; }

  internal void InitControl(
    CApCableFrameAttachmentRetriever frameAttachmentRetriever,
    CApFlexParameterController parameterController)
  {
    this.m_isFrameNameChanging = false;
    this.AttachmentFrames = new List<ITxLocatableObject>();
    this.FrameAttachmentRetriever = frameAttachmentRetriever;
    this.ParameterController = parameterController;
    this.InitializeComponent();
    this.m_isControlLoading = false;
    this.AttributeViewModel.InitAttachmentList();
    this.AttributeViewModel.PropertyChanged += new PropertyChangedEventHandler(this.AttributeViewModel_PropertyChanged);
    TxApplication.Options.Units.LinearUnitsChanged += new TxUnitsOptions_LinearUnitsChangedEventHandler(this.Units_LinearUnitsChanged);
    this.attachmentLengthTitle.Header = (object) $"{this.attachmentLengthTitle.Header?.ToString()} ({TxApplication.Options.Units.LinearUnitName})";
    this.InitViewModel();
  }

  public void UpdateAttachmentDataListWithCable(ITxCable cable)
  {
    if (cable == null)
      return;
    this.AttributeViewModel.ClearAttachments();
    this.AttributeViewModel.SetAttachmentList(CApFLEXAttachment.CreateAttachmentsFromCable(cable));
    this.UpdateAttachmentFlexGrid();
  }

  public void UpdateLinearUnitText()
  {
    this.attachmentLengthTitle.Header = (object) (CApFLEXStringTable.AttachmentLengthHeader + CApCableUtility.LinearUnitHeaderText());
  }

  public void EndOfLoading() => this.UpdateAttachmentFlexGrid();

  public void InitViewModel()
  {
    this.AttachmentViewModel.Location = this.ParameterController.AttachmentLocation;
    this.AttachmentViewModel.LengthFromStart = this.AttributeViewModel.Length * 0.5;
    this.AttachmentViewModel.SecondaryLengthFromStart = this.AttributeViewModel.Length * 0.25;
    this.AttachmentViewModel.RotatingRotationAxis = this.ParameterController.RotatingRotationAxis;
    this.AttachmentViewModel.RotatingSlidingRotationAxis = this.ParameterController.RotatingSlidingRotationAxis;
    this.AttachmentViewModel.SpringConstant = this.ParameterController.RetractSystemSpringConstant;
    this.AttachmentViewModel.MinRetractedLength = this.ParameterController.RetractSystemMinRetractLength;
    this.AttachmentViewModel.MaxRetractedLength = this.ParameterController.RetractSystemMaxRetractLength;
    this.AttachmentViewModel.IsEditableAttachment = this.AttributeViewModel.AreEquipmentParametersEnabled;
  }

  public void UpdateUserControl() => this.UpdateAttachmentFlexGrid();

  public void UpdateAttachmentFlexGrid()
  {
    if (!this.AttributeViewModel.IsAttachmentListNull())
    {
      this.ReorderAttachmentDataList(out int _);
      this.fgAttachmentFlexGrid.ItemsSource = (IEnumerable) null;
      this.fgAttachmentFlexGrid.ItemsSource = (IEnumerable) this.AttributeViewModel.RawAttachmentList();
      this.fgAttachmentFlexGrid.Refresh();
    }
    if (this.fgAttachmentFlexGrid.Items.Count <= 0)
      return;
    this.fgAttachmentFlexGrid.SelectedIndex = 0;
  }

  private void ReorderAttachmentDataList(out int newSelectAttachmentIndex)
  {
    newSelectAttachmentIndex = 0;
    if (this.AttributeViewModel.RawAttachmentList().Count == 0)
      return;
    int index = this.fgAttachmentFlexGrid.SelectedIndex;
    if (index == -1 || this.AttributeViewModel.RawAttachmentList().Count <= index)
      index = 0;
    ITxLocatableObject fixedFrame = this.AttributeViewModel.RawAttachmentList()[index].FixedFrame;
    List<CApFLEXAttachment> orderedAttachments = new List<CApFLEXAttachment>();
    CApCableUtility.OrderedAttachmentList(this.AttributeViewModel.RawAttachmentList(), out orderedAttachments);
    this.AttributeViewModel.SetAttachmentList(orderedAttachments);
    int num = 0;
    foreach (CApFLEXAttachment rawAttachment in this.AttributeViewModel.RawAttachmentList())
    {
      if (rawAttachment.FixedFrame != fixedFrame)
        ++num;
      else
        break;
    }
    newSelectAttachmentIndex = num;
  }

  private void UpdateEditRemoveAttachmentSensitivity()
  {
    if (this.AttributeViewModel.StartFrame == null || this.AttributeViewModel.EndFrame == null)
    {
      this.AttributeViewModel.IsRemoveAttachmentEnabled = false;
      this.AttributeViewModel.IsEditAttachmentEnabled = false;
    }
    else if (!this.AttributeViewModel.IsAttachmentListNull() && this.AttributeViewModel.CountAttachments() > 0)
    {
      this.AttributeViewModel.IsRemoveAttachmentEnabled = true;
      this.AttributeViewModel.IsEditAttachmentEnabled = true;
    }
    else
    {
      this.AttributeViewModel.IsRemoveAttachmentEnabled = false;
      this.AttributeViewModel.IsEditAttachmentEnabled = false;
    }
  }

  public void UpdateAddRemoveAttachmentSensitivity()
  {
    this.UpdateEditRemoveAttachmentSensitivity();
    if (this.AttributeViewModel.StartFrame == null || this.AttributeViewModel.EndFrame == null)
      this.AttributeViewModel.IsAddAttachmentEnabled = false;
    else
      this.AttributeViewModel.IsAddAttachmentEnabled = true;
  }

  public void DidDialogClose()
  {
    this.AttributeViewModel.PropertyChanged -= new PropertyChangedEventHandler(this.AttributeViewModel_PropertyChanged);
    TxApplication.Options.Units.LinearUnitsChanged -= new TxUnitsOptions_LinearUnitsChangedEventHandler(this.Units_LinearUnitsChanged);
    this.UnregisterAttachmentFramesNotifications();
  }

  private void LaunchAttachmentWindow()
  {
    this.IsAttachmentDialogLaunching = true;
    if (this.AttachmentViewModel.LengthFromStart == 0.0)
      this.AttachmentViewModel.LengthFromStart = this.AttributeViewModel.Length * 0.5;
    if (this.AttachmentViewModel.SecondaryLengthFromStart == 0.0)
      this.AttachmentViewModel.SecondaryLengthFromStart = this.AttributeViewModel.Length * 0.25;
    this.NewAttachmentWindow = new CUiFLEXAttachmentEditorWindow(this.FrameAttachmentRetriever, this.AttributeViewModel, this.AttachmentViewModel, this.ParameterController);
    ((Window) this.NewAttachmentWindow).Closing += new CancelEventHandler(this.NewAttachmentWindowClosing);
    ((Window) this.NewAttachmentWindow).Show();
    this.IsEnabled = false;
    this.IsAttachmentDialogLaunching = false;
  }

  private void LaunchAttachmentWindow(CApFLEXAttachment attachment)
  {
    this.IsAttachmentDialogLaunching = true;
    this.NewAttachmentWindow = new CUiFLEXAttachmentEditorWindow(this.FrameAttachmentRetriever, this.AttributeViewModel, this.AttachmentViewModel, this.ParameterController, attachment);
    ((Window) this.NewAttachmentWindow).Closing += new CancelEventHandler(this.NewAttachmentWindowClosing);
    ((Window) this.NewAttachmentWindow).Show();
    this.IsEnabled = false;
    this.IsAttachmentDialogLaunching = false;
  }

  private void RegisterAttachmentFrameNotifications(ITxLocatableObject attachmentFrame)
  {
    ((ITxObject) attachmentFrame).NameChanged += new TxObject_NameChangedEventHandler(this.Frame_NameChanged);
    ((ITxObject) attachmentFrame).Deleted += new TxObject_DeletedEventHandler(this.Frame_Deleted);
  }

  private void UnregisterAttachmentFramesNotifications()
  {
    foreach (ITxLocatableObject attachmentFrame in this.AttachmentFrames)
      this.UnregisterAttachmentFrameNotifications(attachmentFrame);
  }

  private void UnregisterAttachmentFrameNotifications(ITxLocatableObject attachmentFrame)
  {
    ((ITxObject) attachmentFrame).NameChanged -= new TxObject_NameChangedEventHandler(this.Frame_NameChanged);
    ((ITxObject) attachmentFrame).Deleted -= new TxObject_DeletedEventHandler(this.Frame_Deleted);
  }

  private void UpdateRegistrationFramesNotifications()
  {
    this.UnregisterAttachmentFramesNotifications();
    this.AttachmentFrames.Clear();
    foreach (CApFLEXAttachment capFlexAttachment in this.AttributeViewModel.RawAttachmentList().Where<CApFLEXAttachment>((Func<CApFLEXAttachment, bool>) (a => a.Location == CApFLEXAttachmentLocation.AlongCable)))
    {
      ITxLocatableObject fixedFrame = capFlexAttachment.FixedFrame;
      this.AttachmentFrames.Add(fixedFrame);
      this.RegisterAttachmentFrameNotifications(fixedFrame);
    }
  }

  private void UpdateStartLocatedAttachmentFrame()
  {
    this.AttributeViewModel.ChangeStartLocatedAttachmentFrame();
  }

  private void UpdateEndLocatedAttachmentFrame()
  {
    this.AttributeViewModel.ChangeEndLocatedAttachmentFrame();
  }

  private void Units_LinearUnitsChanged(
    object sender,
    TxUnitsOptions_LinearUnitsChangedEventArgs args)
  {
    this.UpdateLinearUnitText();
  }

  private void AttributeViewModel_PropertyChanged(object sender, PropertyChangedEventArgs e)
  {
    if (this.AttributeViewModel.IsCreationParameter(e.PropertyName))
      this.UpdateAddRemoveAttachmentSensitivity();
    if (e.PropertyName == "AttachmentDataList")
    {
      this.UpdateAddRemoveAttachmentSensitivity();
      this.UpdateRegistrationFramesNotifications();
    }
    else if (e.PropertyName == "StartFrame")
    {
      this.UpdateStartLocatedAttachmentFrame();
    }
    else
    {
      if (!(e.PropertyName == "EndFrame"))
        return;
      this.UpdateEndLocatedAttachmentFrame();
    }
  }

  private void TxNumericEditBoxAttachmentLength_LostFocus(object sender, RoutedEventArgs e)
  {
    this.ReorderAttachmentDataList(out int _);
    this.UpdateAttachmentFlexGrid();
    this.UpdateGridAttachmentLengthReadOnlyStatus();
  }

  private void TxNumericEditBoxAttachmentLength_KTentativeValueChanged(
    object sender,
    TxNumericEditBoxCtrl_TentativeValueChangedEventArgs args)
  {
    if (this.m_isControlLoading || args.TentativeValue == 0.0 || args.TentativeValue <= 0.0 || args.TentativeValue >= 30000.0)
      return;
    this.AttributeViewModel.RawAttachmentList()[this.fgAttachmentFlexGrid.SelectedIndex].LengthFromStart = args.TentativeValue * TxApplication.Options.Units.LinearMultiplier;
  }

  private void UpdateGridAttachmentLengthReadOnlyStatus()
  {
    int selectedIndex = this.fgAttachmentFlexGrid.SelectedIndex;
    if (selectedIndex <= -1 || selectedIndex >= this.AttributeViewModel.RawAttachmentList().Count)
      return;
    this.attachmentLengthTitle.IsReadOnly = this.AttributeViewModel.StartFrame == null || this.AttributeViewModel.EndFrame == null || !this.AttributeViewModel.AreEquipmentParametersEnabled || this.AttributeViewModel.RawAttachmentList()[selectedIndex].Location != 0;
  }

  private void btnAddAttachment_Click(object sender, RoutedEventArgs e)
  {
    this.LaunchAttachmentWindow();
    this.AttachmentDialogOpened();
  }

  public void NewAttachmentWindowClosing(object sender, CancelEventArgs e)
  {
    this.IsEnabled = true;
    CUiFLEXAttachmentEditorWindow attachmentEditorWindow = sender as CUiFLEXAttachmentEditorWindow;
    if (attachmentEditorWindow.IsCreated && attachmentEditorWindow.IsCreationMode)
    {
      List<CApFLEXAttachment> orderedAttachments = new List<CApFLEXAttachment>();
      this.AttributeViewModel.AddAttachment(attachmentEditorWindow.Attachment);
      CApCableUtility.OrderedAttachmentList(this.AttributeViewModel.RawAttachmentList(), out orderedAttachments);
      this.AttributeViewModel.SetAttachmentList(orderedAttachments);
      this.UpdateAttachmentFlexGrid();
    }
    else if (attachmentEditorWindow.IsCreated && !attachmentEditorWindow.IsCreationMode)
    {
      IList selectedItems = this.fgAttachmentFlexGrid.SelectedItems;
      if (selectedItems.Count == 1)
      {
        CApFLEXAttachment capFlexAttachment = selectedItems[0] as CApFLEXAttachment;
        List<CApFLEXAttachment> orderedAttachments;
        CApCableUtility.OrderedAttachmentList(this.AttributeViewModel.RawAttachmentList(), out orderedAttachments);
        if (orderedAttachments != null)
        {
          for (int index = orderedAttachments.Count - 1; index > -1; --index)
          {
            if (orderedAttachments[index].FixedFrame == capFlexAttachment.FixedFrame)
            {
              orderedAttachments.RemoveAt(index);
              break;
            }
          }
          this.AttributeViewModel.SetAttachmentList(orderedAttachments);
          this.AttributeViewModel.AddAttachment(attachmentEditorWindow.Attachment);
          CApCableUtility.OrderedAttachmentList(this.AttributeViewModel.RawAttachmentList(), out orderedAttachments);
          this.AttributeViewModel.SetAttachmentList(orderedAttachments);
          this.UpdateAttachmentFlexGrid();
        }
        else
        {
          orderedAttachments = new List<CApFLEXAttachment>();
          this.AttributeViewModel.AddAttachment(attachmentEditorWindow.Attachment);
          CApCableUtility.OrderedAttachmentList(this.AttributeViewModel.RawAttachmentList(), out orderedAttachments);
          this.AttributeViewModel.SetAttachmentList(orderedAttachments);
          this.UpdateAttachmentFlexGrid();
        }
      }
    }
    ((Window) this.NewAttachmentWindow).Closing -= new CancelEventHandler(this.NewAttachmentWindowClosing);
    this.NewAttachmentWindow = (CUiFLEXAttachmentEditorWindow) null;
    this.AttachmentDialogClosed();
  }

  private void btnRemoveAttachment_Click(object sender, RoutedEventArgs e)
  {
    IList selectedItems = this.fgAttachmentFlexGrid.SelectedItems;
    if (selectedItems.Count > 0)
    {
      for (int index = selectedItems.Count - 1; index >= 0; --index)
        this.AttributeViewModel.RemoveAttachment(selectedItems[index] as CApFLEXAttachment);
    }
    this.UpdateAddRemoveAttachmentSensitivity();
    this.UpdateAttachmentFlexGrid();
  }

  private void btnEditAttachment_Click(object sender, RoutedEventArgs e)
  {
    IList selectedItems = this.fgAttachmentFlexGrid.SelectedItems;
    CApFLEXAttachment attachment = (CApFLEXAttachment) null;
    if (selectedItems.Count == 1)
    {
      for (int index = selectedItems.Count - 1; index >= 0; --index)
        attachment = selectedItems[index] as CApFLEXAttachment;
    }
    this.LaunchAttachmentWindow(attachment);
    this.AttachmentDialogOpened();
  }

  private void Frame_Deleted(object sender, TxObject_DeletedEventArgs args)
  {
    if (sender == null || !(sender is ITxLocatableObject itxLocatableObject))
      return;
    for (int index = this.AttributeViewModel.CountAttachments() - 1; index >= 0; --index)
    {
      if (this.AttributeViewModel.RawAttachmentList()[index].FixedFrame == itxLocatableObject)
        this.AttributeViewModel.RemoveAttachment(this.AttributeViewModel.RawAttachmentList()[index]);
    }
    this.UpdateAttachmentFlexGrid();
  }

  private void Frame_NameChanged(object sender, TxObject_NameChangedEventArgs args)
  {
    if (!this.m_isFrameNameChanging)
    {
      if (sender == null || !(sender is ITxLocatableObject))
        return;
      this.m_isFrameNameChanging = true;
      this.UpdateAttachmentFlexGrid();
    }
    else
      this.m_isFrameNameChanging = false;
  }

  private void AttachmentFrameDidChanged(ITxLocatableObject obj)
  {
    if (obj == null)
      return;
    this.AttributeViewModel.CableStatusAnalysis.CableFrameAttachmentRetriever.UpdateFrameAttachmentRegistry(obj);
  }

  private void fgAttachmentFlexGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
  {
    this.AttributeViewModel.IsEditAttachmentEnabled = this.fgAttachmentFlexGrid.SelectedItems.Count == 1;
    this.UpdateGridAttachmentLengthReadOnlyStatus();
  }

  private void fgAttachmentFlexGrid_Loaded(object sender, RoutedEventArgs e)
  {
    if (this.fgAttachmentFlexGrid.Items.Count <= 0)
      return;
    this.fgAttachmentFlexGrid.SelectedIndex = 0;
  }

  [DebuggerNonUserCode]
  [GeneratedCode("PresentationBuildTasks", "4.0.0.0")]
  public void InitializeComponent()
  {
    if (this._contentLoaded)
      return;
    this._contentLoaded = true;
    Application.LoadComponent((object) this, new Uri("/DnProcessSimulateCommands;component/flexibles/usercontrols/capcableattachmentsusercontrol.xaml", UriKind.Relative));
  }

  [DebuggerNonUserCode]
  [GeneratedCode("PresentationBuildTasks", "4.0.0.0")]
  [EditorBrowsable(EditorBrowsableState.Never)]
  void IComponentConnector.Connect(int connectionId, object target)
  {
    switch (connectionId)
    {
      case 1:
        this.attachmentsStackPanel = (StackPanel) target;
        break;
      case 2:
        this.fgAttachmentFlexGrid = (DataGrid) target;
        this.fgAttachmentFlexGrid.SelectionChanged += new SelectionChangedEventHandler(this.fgAttachmentFlexGrid_SelectionChanged);
        this.fgAttachmentFlexGrid.Loaded += new RoutedEventHandler(this.fgAttachmentFlexGrid_Loaded);
        break;
      case 3:
        this.attachmentLengthTitle = (DataGridTemplateColumn) target;
        break;
      case 5:
        this.addAttachmentGrid = (Grid) target;
        break;
      case 6:
        this.btnAddAttachment = (Button) target;
        this.btnAddAttachment.Click += new RoutedEventHandler(this.btnAddAttachment_Click);
        break;
      case 7:
        this.btnRemoveAttachment = (Button) target;
        this.btnRemoveAttachment.Click += new RoutedEventHandler(this.btnRemoveAttachment_Click);
        break;
      case 8:
        this.btnEditAttachment = (Button) target;
        this.btnEditAttachment.Click += new RoutedEventHandler(this.btnEditAttachment_Click);
        break;
      default:
        this._contentLoaded = true;
        break;
    }
  }

  [DebuggerNonUserCode]
  [GeneratedCode("PresentationBuildTasks", "4.0.0.0")]
  [EditorBrowsable(EditorBrowsableState.Never)]
  void IStyleConnector.Connect(int connectionId, object target)
  {
    if (connectionId != 4)
      return;
    ((UIElement) target).LostFocus += new RoutedEventHandler(this.TxNumericEditBoxAttachmentLength_LostFocus);
    ((TxNumericEditBoxControl) target).TentativeValueChanged += new TxNumericEditBoxCtrl_TentativeValueChangedEventHandler(this.TxNumericEditBoxAttachmentLength_KTentativeValueChanged);
  }
}
